<?php
/**
 * GoodsCatService.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2021/1/17- 下午4:37
 */

namespace common\jobs\services;


use common\jobs\models\PddGoodsCats;
use common\jobs\models\PddMallProduct;
use yii\helpers\ArrayHelper;

class GoodsCatService
{
    /**
     * 返回指定pid的当前类目下分类信息
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getCatesList(int $cid)
    {
        return PddGoodsCats::find()
            ->select(['cat_id','cat_name','level','is_parent'])
            ->where(['parent_cat_id'=> $cid])
            ->asArray()->all();
    }


    /**
     * 获取当前店铺使用过的类目
     * @param int $uid
     * @param int $mall_id
     * @return array
     */
    public function getShopUsedCatList(int $uid,int $mall_id)
    {
        $cidList = PddMallProduct::find()->select(['cat_id'])->where([
            'uid' => $uid,
            'mall_id' =>$mall_id
        ])->groupBy('cat_id')->all();

        $myCatList = [];
        foreach($cidList as $c => $item)
        {
            $cidArr = $this->getCatesByCid($item->cat_id);
            $cidArr = ArrayHelper::getColumn($cidArr,'name');

            $tmp['cid'] = $item->cat_id;
            if(count($cidArr))
            {
                $tmp['name'] = implode('->',$cidArr);
            }
            array_push($myCatList,$tmp);
            unset($tmp);
        }

        return $myCatList;

    }



    /**
     * 获取当前叶子类目的上级所有父类目信息
     * @param int $cid
     * @param array $items
     * @return array
     */
    public function getCatesByCid(int $cid,array &$items =[])
    {
        $itemInfo = PddGoodsCats::findOne(['cat_id'=>$cid]);

        if($itemInfo)
        {
            array_push($items,['id'=>$itemInfo->cat_id,'name'=>$itemInfo->cat_name]);
        }
        if(isset($itemInfo->parent_cat_id) && $itemInfo->parent_cat_id > 0)
        {
            $this->getCatesByCid($itemInfo->parent_cat_id,$items);
        }

        return array_reverse($items);
    }


    /**
     * 通过叶子分类获取顶级分类下的所有子分类
     * @param int $cid
     * @param array $cids
     * @return array
     */
    public function getAllChildCidByTopCid(int $cid,array &$cids =[])
    {
        $itemInfo = PddGoodsCats::findOne(['cat_id'=>$cid]);
        if($itemInfo)
        {
            array_push($cids,$itemInfo->cat_id);
            $itemChildCats = PddGoodsCats::find()->where(['parent_cat_id'=>$itemInfo->cat_id])->all();

            if($itemChildCats)
            {
                foreach ($itemChildCats as $k => $item)
                {
                    array_push($cids,$item->cat_id);
                    $this->getAllChildCidByTopCid($item->cat_id,$cids);
                }
            }
        }
        return $cids;
    }

}